<!--
 * @Description: 
 * @Date: 2025-09-18 14:34:48
 * @LastEditTime: 2025-10-09 10:21:09
-->
<!--
 * @Description: 
 * @Date: 2025-09-18 14:34:48
 * @LastEditTime: 2025-09-24 09:00:37
-->
<template>
    <div class="dialogueBox flex flex-col">
        <van-nav-bar :title="callWord[pathType].title" style="background: transparent" left-arrow
            @click-left="onClickLeft"></van-nav-bar>
        <div class="w-100% flex-1 overflow-hidden box-border flex flex-col items-start overflow-hidden">
            <div class="flex flex-col mt-40px items-start  px-20px">
                <span class="font-bold text-20px color-#000">Hi，我是你的AI助手！</span>
                <span class="color-#788595">有问题欢迎随时向我提问。</span>
            </div>
            <div class="w-100% mt-20px flex-1 pt-10px box-border flex flex-col overflow-hidden relative">
                <!-- <div class="w-100% px-20px">
                    <div class="w-100% color-#788595 flex justify-between">
                        <span class="">你可以这样问</span>
                        <span class="mr-20px"><van-icon name="replay" />换一批</span>
                    </div>
                </div> -->
                <!-- <div class="w-100% px-20px mt-5px ">
                    <p class="p-10px bg-#EFEFEF mb-8px text-left border-rd-10px flex justify-between items-center" v-for="value in callWord[pathType].info">
                        {{ value }} <van-icon name="arrow" size="16" /></p>
                    
                </div> -->
                <div class="flex-1 w-100% px-20px pb-80px mt-20px  overflow-y-auto  box-border" ref="scrollDom">
                    <div class="w-100% flex flex-col  gap-20px mt-20px" v-if="messages.length > 0"
                        v-for="msg in messages" :key="msg.sessionId">
                        <div class="arrow_box_right ">
                            <p class="m-0 max-w-100px min-w-40px min-h-15px max-w-250px  overflow-hidden text-left"
                                style="word-wrap: break-word;">{{
                                    msg.title }}</p>
                        </div>
                        <div class="arrow_box_left">
                            <p v-if="msg.data" class="m-0 min-w-40px min-h-15px max-w-250px overflow-hidden text-left"
                                style="word-wrap: break-word; white-space: pre-wrap;" v-html="msg.data">

                            </p>
                            <a-spin v-else tip="努力思考中..." />
                        </div>
                    </div>
                </div>
                <div
                    class="bg-#ffffff p-10px flex items-center gap-10px  fixed bottom-0 left-0 h-70px w-100% box-border overflow-hidden">
                    <div class="w-100% border-rd-10 overflow-hidden bg-transparent" style="border:2px solid #75A8FF">
                        <van-search
                            class="w-100% bg-transparent!   box-border p-0! pr-2px!  focus:outline-none input-focus transition-all"
                            v-model="inputValue" placeholder="点击输入聊天内容" wrap-with-form>
                        </van-search>
                    </div>
                    <!-- <input v-model="inputValue" placeholder="点击输入聊天内容"
                         
                        type="text" inputmode="text"
                        class="flex-1  box-border px-15px py-5px border-rd-10  focus:outline-none input-focus transition-all"
                        style="border:2px solid #75A8FF"> -->
                    <van-button icon="back-top" :disabled="loading" round size="small" type="primary"
                        @click="handleSubmit" />
                </div>
            </div>
        </div>


    </div>
</template>
<script setup>
import { ref, onMounted, onUnmounted, nextTick } from "vue"
import ReconnectingWebSocket from 'reconnecting-websocket';
import { useRouter, useRoute } from "vue-router";
const inputValue = ref()
const socket = ref()
const loading = ref(false);
const router = useRouter();
const scrollDom = ref(null);
const messageRefs = ref([]);
const route = useRoute()
const pathType = route.query.path
const callWord = {
    "wenda": {
        title: "AI问答",
        info: [
            '给于客户画像和营销策略输出',
            '请输入手机号或身份证'
        ]
    },
    "yhhx": {
        title: "拓客星睿",
        info: [
            '给于客户画像和营销策略输出',
            '请输入手机号或身份证'
        ]
    },
    "xiaoxi": {
        title: "工单巧语",
        info: [
            '个性化营销话术的生成',
            '请输入手机号'
        ]
    },
    "zhihui": {
        title: "智识快答",
        info: [
            '专注知识问答',
            '想要一条便宜的宽带,我推荐什么？'
        ]
    },
    "zhengqi": {
        title: "政企慧能",
        info: [
            'xxxxxxxxxxx',
            'xxxxxxxxxxxxxxx'
        ]
    },
    "jihao": {
        title: "靓号精灵",
        info: [
            'xxxxxxxxxxx',
            'xxxxxxxxxxxxxxx'
        ]
    }
}

const messages = ref([

]);
const handleSubmit = () => {
    loading.value = true
    messages.value.push({
        sessionId: inputValue.value,
        title: inputValue.value,
        data: ''
    })
    socket.value.send(inputValue.value);
    scrollToBottom()
}
onMounted(() => {
    loading.value = true
    initWebSocket(pathType)
    if (pathType == 'wenda') {
        inputValue.value = route.query.content
        handleSubmit()
    }
})
onUnmounted(() => {
    if (socket.value) {
        socket.value.close()
    }
    inputValue.value = null
})
const initWebSocket = (pathType) => {
    // 连接后端 WebSocket 服务
    const wsUrl = `ws://sn.wgt.10086.cn/snsst/chudayi/ya/checkup/wsApi/ws/9999/${pathType}/9999`; // 对应后端 @ServerEndpoint 的 value
    const options = {
        // WebSocket: WebSocket, // 允许你指定一个自定义的 WebSocket 构造函数，通常用于在不同环境中使用不同的 WebSocket 实现
        connectionTimeout: 10000, // 连接初始尝试的超时时间 10000
        maxRetries: 100, // 连接失败后，最大允许的重试次数 100
        maxReconnectionDelay: 10000, // 这是连接重试之间的最大延迟
        minReconnectionDelay: 1000, // 连接重试之间的最小延迟  
        automaticOpen: true,  // 自动连接
        debug: false // enables debug output
    };

    // 方案1：使用原生 WebSocket
    socket.value = new ReconnectingWebSocket(wsUrl, [], options);


    socket.value.onopen = (event) => {
        console.log('WebSocket 连接成功', event);
        loading.value = false


    };
    socket.value.onmessage = (event) => {
        loading.value = false
        let response = JSON.parse(event.data)
        if (response.content == "**") {
            response.content = "\n"
        }
        if (response.content == ">>>") {
            response.content = response.content.replace(">>>", "")
        }
        if (response.content == '数据发送结束') {
            return
        }
        messages.value[messages.value.length - 1].data += response.content
        inputValue.value = ""
        scrollToBottom()
    };

    socket.value.onclose = (event) => {
        console.log('WebSocket 连接关闭', event);
    };
    socket.value.onerror = (error) => {
        console.error('WebSocket 错误', error);
    };
}
const onClickLeft = () => {
    router.push("/dashboard");
}


const scrollToBottom = () => {
    nextTick(() => {
        scrollDom.value.scrollTop = scrollDom.value.scrollHeight;
    })

};
</script>

<style scoped>
.dialogueBox {
    width: 100%;
    height: 100%;
    background-image: url("../assets/img/dialogueBox.png");
    background-size: cover;


}

.arrow_box_right {
    position: relative;
    background: #4278FF;
    padding: 10px;
    display: flex;
    align-items: center;
    border-radius: 10px;
    align-self: flex-end;
    color: #fff;


}

.arrow_box_right:after {
    left: 100%;
    top: 50%;
    border: solid transparent;
    content: "";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
    border-color: rgba(66, 120, 255, 0);
    border-left-color: #4278FF;
    border-width: 5px;
    margin-top: -5px;
}

.arrow_box_left {
    position: relative;
    background: #ffffff;
    display: flex;
    align-items: center;
    padding: 10px;
    border-radius: 10px;
    align-self: flex-start;
    border: none;

}

.arrow_box_left:after {
    right: 100%;
    top: 50%;
    border: solid transparent;
    content: "";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
    border-color: rgba(66, 120, 255, 0);
    border-right-color: #ffffff;
    border-width: 5px;
    margin-top: -5px;
    overflow: hidden;
}

.ant-spin-text {
    font-size: 12px;
}

:deep(.van-nav-bar .van-icon),
:deep(.van-nav-bar__title) {
    color: #000;
}

:deep(.van-hairline--bottom:after) {

    border: none !important;
}
</style>